var express = require('express');
var router = express.Router();
var utils = require('../functions/utils');
var replaceProhibitedWords = require('../functions/replaceProhibitedWords');
var findS3File = require('../functions/findS3File');
var async = require('async');


router.post('/', function(req,res)
{

	var sessionId		= req.body.sessionId;		utils.checkParamValue('sessionId' , sessionId);

	var path			= req.body.path;			utils.checkParamValue('path' , path);
	var videoFileId		= req.body.videoFileId;		utils.checkParamValue('videoFileId' , videoFileId);
	var videoFileExt	= req.body.videoFileExt;	utils.checkParamValue('videoFileExt' , videoFileExt);
	var scriptFileId	= req.body.scriptFileId;	utils.checkParamValue('scriptFileId' , scriptFileId);
	var scriptFileExt	= req.body.scriptFileExt;	utils.checkParamValue('scriptFileExt' , scriptFileExt);
	var articleState	= req.body.articleState;	utils.checkParamValue('articleState' , articleState);

	// 이하 옵션 
	var articleBody		= req.body.articleBody;	
	var tagList			= req.body.tagList;
	var latitude		= req.body.latitude;
	var longitude		= req.body.longitude;

	utils.callLog2(req);

	// trace log 에 추가정보를 넣어야 함. -> 성공했을 때만 넣도록 위치변경
	//utils.sessionTraceLogWithParam(req , req.body.editLog);
	
	// 금지어 체크
	//utils.checkProhibitedWord(articleBody);
	articleBody = replaceProhibitedWords(articleBody);


	var async = require('async');
	async.waterfall([
		function(cb)
		{
			utils.getUserIdWithSessionId(sessionId , cb);
		}
		,function(userId , cb) {
			if(!userId)
			{
				var err = new Error('Invalid session ID : ' + sessionId);
				err.code = '522';
				throw err;
			}

			///////////////////////////본 루틴//////////////////////////////


			// file check 후 디비작업 .
			async.series(
				[
					// video file check
					function(videoCB)
					{
						findS3File(path + videoFileId + '.' + videoFileExt , videoCB);
					}
					// script file check
					,function(scriptCB)
					{
						findS3File(path + scriptFileId + '.' + scriptFileExt , scriptCB);
					}
				]
				,function(err, results) 
				{
					if(err){ throw err; }

					// 업로드되지 않은 파일이 있을 경우.
					if(!arguments['1'][0] || !arguments['1'][1])
					{
						var ret = {code: '556' , body: {}};

						ret.body.videoFile = Number(arguments['1'][0]);
						ret.body.scriptFile = Number(arguments['1'][1]);

						res.json(ret);
						res.end();

						// 핸들러 통하지 않으므로 디비로그에 직접때려 넣는다.
						utils.errorLog(req , '556' , 'videoFile: ' + arguments['1'][0] + ', scriptFile: ' + arguments['1'][1]);

						// post 함수종료. 
						return;
					}

					// insert 하는 항목이 있으므로 master
					global.master_db.connection.getConnection(function(err,connection)
					{
						if(err) { throw err; }

						var input_param = [global.config.region_id , userId , sessionId , videoFileId , videoFileExt , scriptFileId , scriptFileExt ,articleBody , articleState ,tagList , latitude , longitude];
						var sql = 'call api_registerArticleWithSessionIdNew(?,?,?,?,?,?,?,?,?,?,?,?,@result); select @result as result';
						var query = connection.query(sql, input_param , function (err, rows) 
						{
							connection.release();
							if(err) { throw err; }

							var ret = {};	

							switch(rows[1][0].result)
							{
								case 204:
									var err = new Error('previously used file IDs [ video: ' +videoFileId+ ', script: ' +scriptFileId+']' );
									err.code = '204';
									throw err;
									break;
								case 523:
									var err = new Error('unregistered fild IDs [ video: ' +videoFileId+ ', script: ' +scriptFileId+']' );
									err.code = '523';
									throw err;
									break;
								// 에러가 아니면 result = articleID
								default:
									// log 에 articleId 추가 - 기존에는 editLog안보내는 버전대비 체크필요.
									if(utils.isValid(req.body.editLog))
									{
										req.body.editLog.articleId = rows[1][0].result;
										// editing log 추가
										utils.sessionTraceLogWithParam(req , req.body.editLog);
									}
									else
									{
										// log 에 articleId 만 넣어준다.
										var editLog = {articleId: rows[1][0].result};
										utils.sessionTraceLogWithParam(req , editLog);
									}

									ret.code = '202';
							}

							res.json(ret);
							res.end();

						}); // query

					}); // getConnection

				} // series result function

			);// series 

			////////////////////////////////////////////////////////////////////////

		}
	]); //waterfall
	
}); // post

module.exports = router;